<template>
    <view class="page">
        <view class="box">
            <u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1"
                width="184" height="249">
                <div class="upload">
                    <image :src="imgApi+'images/wallet/icon-28.svg'" mode=""></image>添加海报
                    <view class="jy">建议尺寸825*1125px</view>
                </div>
            </u-upload>
            <view class="box-item flex">
                调整小程序码位置
                <u-radio-group v-model="form.type_1" placement="row">
                    <u-radio v-for="(item, index) in radiolist1" :key="index" :label="item.name" :name="item.value"
                        activeColor="#FFBB50" labelSize="13">
                    </u-radio>
                </u-radio-group>
            </view>
            <view class="box-item flex">
                小程序码文字颜色
                <u-radio-group v-model="form.type_2" placement="row">
                    <u-radio v-for="(item, index) in radiolist2" :key="index" :label="item.name" :name="item.value"
                        activeColor="#FFBB50" labelSize="13">
                    </u-radio>
                </u-radio-group>
            </view>
            <view class="box-item flex">
                小程序码背景颜色
                <u-radio-group v-model="form.type_3" placement="row">
                    <u-radio v-for="(item, index) in radiolist3" :key="index" :label="item.name" :name="item.value"
                        activeColor="#FFBB50" labelSize="13">
                    </u-radio>
                </u-radio-group>
            </view>
        </view>
        <canvas canvas-id="myCanvas" style="width: 368px; height: 489px;"></canvas>
        <view class="bottom">
            <view class="btn" @click="handleSave">保存至手机相册</view>
        </view>
    </view>
</template>
<script>
import { getQRCode } from "@/utils/request.js";
export default {
    data() {
        return {
            imgApi:this.$config.imgApi,
            filePath: '',
            id: '',
            form: {
                type_1: 1,
                type_2: 1,
                type_3: 1
            },
            fileList1: [],
            radiolist1: [
                { name: "左", value: 1 },
                { name: "中", value: 2 },
                { name: "右", value: 3 },
            ],
            radiolist2: [
                { name: "黑色", value: 1 },
                { name: "白色", value: 2 },
            ],
            radiolist3: [
                { name: "透明", value: 1 },
                { name: "白色", value: 2 },
            ],
        }
    },
    onLoad(options) {
        this.id = options.id;
    },
    methods: {
        async getQRCode(data) {
            return await getQRCode(data);
        },
        saveArrayBufferToFile(img) {
            let base64 = img.replace(/^data:image\/\w+;base64,/, "");
            var number = Math.random();
            let filePath = wx.env.USER_DATA_PATH + "/qrImg" + number + ".png";
            uni.getFileSystemManager().writeFile({
                filePath: filePath, //创建一个临时文件名
                data: base64, //写入的文本或二进制数据
                encoding: "base64", //写入当前文件的字符编码
                success: (res) => {
                    console.log('res:', res, 'filePath:', filePath)
                    this.filePath = filePath
                    uni.showLoading({
                        title: '保存中...',
                        mask: true
                    })
                    this.handleImg()
                }
            })
        },
        base64ToArrayBuffer(base64) {
            // 使用全局的 atob 函数，如果存在的话
            const atob = globalThis.atob || function (b64) {
                let binary = '';
                const bytes = new Uint8Array(new ArrayBuffer(b64.length));
                for (let i = 0; i < b64.length; i++) {
                    bytes[i] = b64.charCodeAt(i);
                }
                return String.fromCharCode.apply(null, bytes);
            };
            const binaryString = atob(base64.split(',')[1]);
            const len = binaryString.length;
            const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            return bytes.buffer;
        },
        async handleImg() {
            let img1 = this.fileList1[0].url
            // 创建画布并获取上下文
            const ctx = uni.createCanvasContext("myCanvas");
            // 定义一个加载图片的异步函数
            const loadImage = async (src) => {
                return new Promise((resolve, reject) => {
                    uni.getImageInfo({
                        src: src,
                        success: resolve,
                        fail: reject,
                    });
                });
            };
            try {
                const res1 = await loadImage(img1);
                ctx.drawImage(res1.path, 0, 0, 368, 489);
                console.log("第一张图片绘制完成");
                const res2 = await loadImage(this.filePath);
                let img_x = ''
                let text_x = ''
                if (this.form.type_1 == 1) {
                    img_x = 0
                    text_x = 30
                } else if (this.form.type_1 == 2) {
                    img_x = 100
                    text_x = 130
                } else {
                    img_x = 220
                    text_x = 270
                }
                ctx.drawImage(res2.path, img_x, 265, 150, 150);
                console.log("第二张图片绘制完成");
                // 设置字体样式
                ctx.setFontSize(14); // 设置字体大小
                let color = ''
                if (this.form.type_2 == 1) {
                    color = 'black'
                } else {
                    color = 'white'
                }
                ctx.setFillStyle(color); // 设置字体颜色
                // 绘制第一行文字 "扫码查阅"
                ctx.fillText("扫码查阅", text_x, 433); // (x, y) 是文字的起始位置
                // 绘制第二行文字 "精彩活动等你来"
                ctx.fillText("精彩活动等你来", text_x - 15, 460); // (x, y) 是文字的起始位置
                // 确保所有绘制操作都已提交
                ctx.draw(false, () => {
                    console.log("所有绘制操作已完成，开始生成图片...");
                    uni.canvasToTempFilePath({
                        canvasId: "myCanvas",
                        success: function (res) {
                            console.log("生成图片成功，路径:", res.tempFilePath);
                            uni.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: function () {
                                    uni.hideLoading()
                                    console.log("图片已保存到相册");
                                },
                                fail: function (err) {
                                    uni.hideLoading()
                                    console.error("保存图片失败：", err);
                                },
                            });
                        },
                        fail: function (err) {
                            console.error("生成图片失败：", err);
                        },
                    });
                });
            } catch (error) {
                console.error("加载图片或绘制过程中发生错误：", error);
            }
        },
        getCode() {
            const data = {
                activity_id: this.id,
                page: "pagesB/release/activeDetail",
                is_hyaline: true,
            };
            if (this.form.type_3 == 1) {
                data.is_hyaline = true
            } else {
                data.is_hyaline = false
            }
            this.getQRCode(data).then((res) => {
                if (res) {
                    this.img = res.base64;
                    this.saveArrayBufferToFile(res.base64);
                }
            });
        },
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        async afterRead(event) {
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = this[`fileList${event.name}`][fileListLen];
                this.$set(this[`fileList${event.name}`], fileListLen, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }));
                fileListLen++;
            }
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                let that = this
                let a = uni.uploadFile({
                    url: that.$config.upLoadApi + 'file/imageUpload',
                    filePath: url,
                    name: 'file',
                    formData: {
                        file: url,
                        token: uni.getStorageSync('token'),
                    },
                    success: (res) => {
                        var data = JSON.parse(res.data);
                        uni.hideLoading()
                        if (data.code == 200) {
                            const result = that.$config.showImgApi + data.path;
                            resolve(result);
                        } else {
                            reject(new Error('上传失败')); // 拒绝 Promise
                        }
                    },
                    fail: (err) => {
                        console.error(err);
                        uni.hideLoading();
                        reject(err); // 拒绝 Promise
                    }
                });
            })
        },
        handleSave() {
            if (this.fileList1.length == 0) {
                uni.showToast({
                    title: '请上传海报图！',
                    icon: 'none',
                    mask: true
                })
                return;
            }
            this.getCode()
        },
    }
}
</script>
<style lang="scss" scoped>
.page {
    padding: 28rpx 0;
    canvas {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
    }

    .box {
        width: 626rpx;
        padding: 43rpx 34rpx 0;
        background: #ffffff;
        border-radius: 15rpx;
        margin: 0 auto;

        .box-item {
            padding: 43rpx 0;
            border-top: 1rpx solid#D7D7D7;
            justify-content: space-between;
        }

        ::v-deep.u-upload {
            width: 368rpx;
            margin: 0 auto 58rpx;
        }

        ::v-deep.upload {
            width: 368rpx;
            height: 376rpx;
            background-color: #ffe7ca;
            border: 1rpx solid#FFB850;
            padding-top: 122rpx;
            display: flex;
            justify-items: center;
            align-items: center;
            flex-direction: column;
            font-size: 33rpx;
            border-radius: 16rpx;

            image {
                margin-top: 30rpx;
                width: 104rpx;
                height: 104rpx;
            }

            .jy {
                font-size: 23rpx;
                color: #555555;
                margin-top: 34rpx;
            }
        }

        ::v-deep.u-radio-group {
            .u-radio {
                margin-left: 23rpx;
            }
        }
    }

    .bottom {
        width: 100%;
        position: fixed;
        bottom: 0;
        left: 0;
        padding-bottom: 40rpx;
    }
}
</style>